import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_luban/flutter_luban.dart';
import 'package:flutter_qiniu/flutter_qiniu.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qgchat/common/class/toolFunc/toolFunc.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/common.dart';
import 'package:video_compress/video_compress.dart';

enum PickerType { image, video }

/// 上传文件封装集合
class Upload {
  /// 七牛上传 相册选择 压缩 上传一条龙服务
  static Future<String> qiniu(
    BuildContext context, {
    PickerType type = PickerType.image,
  }) async {
    // 选择图片
    String path;
    try {
      path = await picker(context, ImageSource.gallery, type);
    } catch (e) {
      showToast(e);
      return null;
    }
    if (path == null) return null;
    final file = File(path);

    // 开启加载dialog
    LodingDialog.show(context, '正在努力上传中...');

    // 获取七牛参数
    final res = await CommonApis.qiniuToken();
    final domain = res['data']['domain'];
    final token = res['data']['token'];
    final key = ToolFunc.randomKeyByTimestamp();

    // 上传七牛
    final qiniuPathUrl = await Qiniu.onUpload(file, key, token);

    // 关闭加载dialog
    LodingDialog.hide();

    // 7牛图片
    final url = '$domain/$qiniuPathUrl';

    return url;
  }

  /// 单纯的7牛云上传功能
  static Future<String> qiniuUploadVideo(
    BuildContext context,
    File file,
  ) async {
    if (file == null || file.path == null) {
      throw "没有选择视频";
    }
    final res = await CommonApis.qiniuToken();
    final domain = res['data']['domain'];
    final token = res['data']['token'];
    final key = ToolFunc.randomKeyByTimestamp();
    final path = await Compress.video(context, file);
    LodingDialog.show(context, '上传视频中...');
    final qiniuPathUrl = await Qiniu.onUpload(File(path), key, token);
    LodingDialog.hide();
    final url = '$domain/$qiniuPathUrl';
    return url;
  }

  /// 选择视频
  static Future<File> choiceVideo() async {
    final pickedFile = await ImagePicker.pickVideo(source: ImageSource.gallery);
    if (pickedFile?.path == null) return null;
    final oldVideoInfo = await VideoCompress.getMediaInfo(pickedFile.path);
    if (oldVideoInfo.duration > 10000) throw '只能上传10s内的视频';
    return File(pickedFile.path);
  }

  /// 选择图片 相册or拍照
  static Future<String> picker(
    BuildContext context,
    ImageSource source,
    PickerType type,
  ) async {
    final picker = ImagePicker();

    // 图片
    if (type == PickerType.image) {
      final pickedFile = await ImagePicker.pickImage(source: source);
      if (pickedFile?.path == null) return null;

      final size = (await pickedFile.readAsBytes()).length;
      final onem = 1024 * 1024;

      if (size > onem * 10) {
        throw '图片不能大于10m';
      }
      // if (size > onem * 2 && size < onem * 10) {
      //   LodingDialog.show(context, '压缩图片中...');
      //   final path = await Compress.image(File(pickedFile.path));
      //   LodingDialog.hide();
      //   return path;
      // }
      return pickedFile?.path;
    }

    // 视频
    if (type == PickerType.video) {
      final pickedFile = await ImagePicker.pickVideo(source: source);
      if (pickedFile?.path == null) return null;
      final path = await Compress.video(context, File(pickedFile.path));
      return path;
    }

    return null;
  }
}

///
/// 提示弹窗
///
class LodingDialog {
  // 开启加载dialog
  static show(BuildContext context, String title) {
    showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: Text('$title'),
          content: CupertinoActivityIndicator(),
        );
      },
    );
  }

  // 关闭加载dialog
  static hide() {
    Global.noCtxRoute.navigatorKey.currentState.pop();
  }
}

///
/// 七牛
///
class Qiniu {
  /// 单个文件上传
  ///
  /// [file] 文件
  /// [key] 保存在服务器上的资源唯一标识
  /// [token] 服务器分配的 token
  static Future<String> onUpload(
    File file,
    String key,
    String token, [
    Function(dynamic) onProgress,
  ]) async {
    final qiniu = FlutterQiniu(zone: QNFixedZone.zone2);

    // 上传进度
    onProgress = onProgress ??
        (dynamic percent) {
          // double p = percent;
        };
    qiniu.onProgressChanged().listen(onProgress);

    String resultKey = await qiniu.uploadFile(file.path, key, token);

    return resultKey;
  }

  /// 多个文件上传
  static Future<List<String>> onUploadFiles(
    List<FilePathEntity> entities,
  ) async {
    final qiniu = FlutterQiniu(zone: QNFixedZone.zone1);
    List<String> resultKeys = await qiniu.uploadFiles(entities);

    return resultKeys;
  }
}

///
/// 压缩
///
class Compress {
  /// 图片压缩
  static Future<String> image(File file) async {
    final tempDir = await getTemporaryDirectory();
    CompressObject compressObject = CompressObject(
      imageFile: file,
      path: tempDir.path,
      quality: 85,
      step: 9,
      mode: CompressMode.LARGE2SMALL,
    );
    return await Luban.compressImage(compressObject);
  }

  /// 视频压缩
  static Future<String> video(context, File file) async {
    final oldVideoInfo = await VideoCompress.getMediaInfo(file.path);
    if (oldVideoInfo.duration > 10000) throw '只能上传10s内的视频';
    LodingDialog.show(context, '压缩视频中...');
    final info = await VideoCompress.compressVideo(
      file.path,
      quality: VideoQuality.MediumQuality,
      deleteOrigin: false,
      includeAudio: true,
    );
    if (info == null) throw "压缩失败";
    LodingDialog.hide();
    return info.path;
  }
}
